<!-- 从业者-考试培训-考证报名 -->
<template>
	<view class="container">
		<!-- picker弹窗 -->
		<u-picker v-model="show" :mode="mode" :range="range" @confirm="confirm"></u-picker>

		<!-- 表单区域 -->
		<view class="form-container">
			<u-form :model="form" ref="form" :rules="rules">
				<!-- 报考城市 -->
				<u-field  v-model="form.bkz_bkcs" label="报考城市：" disabled  label-width="160" prop="companyName" placeholder="请输入报考的城市"
					:placeholder-style="placeholderStyle">
				</u-field>

				<!-- 报考等级 -->
				<u-field :readonly="true" v-model="form.bkzLevels" label="报考等级：" label-width="160" prop="companyName" placeholder="请选择报考等级"
					:placeholder-style="placeholderStyle" @click="isShowPicker(0)" :focus="false"  disabled>
				</u-field>

				<!-- 固定分类 -->
				<u-field v-model="form.jdclassfiy" label="鉴定分类：" label-width="160" placeholder="请选择企业鉴定分类"
					:placeholder-style="placeholderStyle" @click="isShowPicker(1)" :focus="false"  disabled>
				</u-field>

				<view class="checkbox-container">
					<text style="font-size: 16px; line-height: 32px;">是否参加培训</text>
					<u-checkbox-group >
						<u-checkbox @change="isTraining" v-model="form.boxchecked" :disabled="false" shape="circle">参加</u-checkbox>
					</u-checkbox-group>
				</view>
			</u-form>
			
			<view class="text-container">
				<text style="font-size: 16px; line-height: 32px;">含培训费：¥{{form.selectedfl.kzl_fortrainprice}}元</text>
				<text style="font-size: 16px; line-height: 32px;">福利赠送：（报名成功后可学习）</text>
				<text style="font-size: 16px; line-height: 32px;">1、在线课程：{{form.selectedflkc}}</text>
				<text style="font-size: 16px; line-height: 32px;">2、练习题库: {{form.selectedfltk}}</text>				
			</view>
			
			<u-gap height="10" bg-color="#e5e5e5"></u-gap>
			
			<!-- 支付明细 -->
			<view class="invitation-popup">
				<!-- 需要支付的详情 -->
				<view class="pay-container">
					<!-- 金额汇总 -->
					<view class="card">
					  <view class="amount-item">
					    <text>{{form.bkz_name}}</text>
					    <text>（{{form.bkzLevels}}）¥{{form.selectedfl.kzl_price ? form.selectedfl.kzl_price : 0 }}</text>
					  </view>
					  <view class="amount-item">
					    <text>培训</text>
					    <text>（{{form.bkzLevels}}）¥{{kzlFortrainprice ? kzlFortrainprice : 0}}</text>
					  </view>
						<u-line color="#a0a2a7" margin="40rpx 0"></u-line>
						<view class="amount-item">
						  <text>订单金额</text>
						  <text>¥{{ form.orderSum.toFixed(2) }}</text>
						</view>
						<view class="amount-item">
						  <text>积分抵扣</text>
						  <text>-¥{{form.orderJf}}</text>
						</view>
						<view class="amount-item">
						  <text>当前积分100，满100可用，单笔最多可用500</text>
						</view>
						
					  <view class="total-amount">
					    <text>需支付：</text>
					    <text class="price">￥{{form.orderPay.toFixed(2)}}</text>
					  </view>
					</view>
					<!-- 支付方式 -->
					<view class="card">
					  <view class="section-title">支付方式</view>
					  
					  <view class="payment-item" @click="selectPayment('wechat')">
					    <u-checkbox 
					      v-model="payment.wechat" 
					      shape="circle"
					      active-color="#03B8CD"
					    ></u-checkbox>
					    <view class="payment-info">
					      <image src="/static/images/wechat-pay.png" class="payment-icon"></image>
					      <text>微信支付</text>
					    </view>
					  </view>
					  
<!-- 					  <view class="payment-item" @click="selectPayment('other')">
					    <u-checkbox 
					      v-model="payment.other" 
					      shape="circle"
					      active-color="#03B8CD"
					    ></u-checkbox>
					    <view class="payment-info">
					      <image src="/static/images/bank-transfer.png" class="payment-icon"></image>
					      <text>钱包余额（¥ 0.00）</text>
					    </view>
					  </view> -->
					</view>
					<!-- 底部支付按钮 -->
<!-- 					<view class="footer">
					  <u-button 
					    type="primary" 
					    shape="circle" 
					    @click="confirmPayment"
					    :disabled="!payment.wechat && !payment.other"
					  >
					    确认支付
					  </u-button>
					</view>		 -->				
				</view>
			</view>

			<!-- 按钮组 -->
			<view class="button-group">
<!-- 				<u-button type="default" @click="handlePrev" shape="circle" :custom-style="customStyleObject">
					上一步
				</u-button> -->
				<u-button type="primary" @click="handleSubmit" :customStyle="customStyleBut" shape="circle" :loading="loading">
					提交
				</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				customStyleBut: {
					backgroundColor: "#03B8CD",
					"color": "#FFF",
				},
				
				loading: false,
				clearable: false,
				// showBusinessTypePicker: false,
				// showAddressPicker: false,
				doorPhotos: [],
				// 步骤条
				stepsList: [{
						name: "手机号"
					},
					{
						name: "营业执照"
					},
					{
						name: "企业信息"
					}
				],
				// 弹出窗口内容
				show: false,
				mode: "selector",
				range: [],
				NumberValue: 0,
				// field控件的样式
				placeholderStyle: "color:#bcbcbc",
				required: true,
				// 按钮组中的样式写法
				customStyleObject: {
					marginRight: '20rpx'
				},		

				form: {
					bkzLevels: '',   ////考证等级
					jdclassfiy: '初次鉴定',
					boxchecked: false,  //是否培训
					orderCode: '', ///订单号
					orderJf: 0, //订单积分
					orderSum: 0, //订单总金额，需要支付
					orderPay: 0,  //需要支付金额
					orderzflx:'' ,///订单支付类型，微信支付，还是钱包余额
					selectedfl:{}, ///所选择的等级福利 
					selectedflkc:'', ////所选择的福利课程
					selectedfltk:'', ///所选择的福利题库

				},
				kzlPrice: 0,
				kzlFortrainprice: 0, //培训金额
				// 企业介绍输入框
				introduction: '',
				currentCount: 0,
				maxCount: 1000,
				// 验证
				rules: {
					companyName: [{
						required: true,
						message: '请输入企业名称',
						trigger: 'blur'
					}]
				},
				// 支付明细
				payment: {
				  wechat: true,
				  other: false
				},
				bkzcode: '', ///考证code
				courseList: [], ///考证明细
				levelRage: [], ///考证等级 
				jdDictCode: '', ///字典code
				jdRange: [], ///鉴定字典内容
				// 微信支付
				appid:'',  ////wx的appid
				nonceStr: '', ///阿布字符串
				package: '', //固定值 
				paySign: '', //微信支付商户号
				signType: '', //统一下单号
				timeStamp: '', //时间戳（单位：秒杀）
			}
		},
		onLoad(options) {
			this.bkzcode = options.bkzcode;
			
		},
		onShow() {
			// 考证内容详情
			this.getbkzDetails()
			// 获取字典鉴定等级
			this.getDictList(0)
		},
		methods: {
			// 考证内容详情
			getbkzDetails() {
				this.$u.api.querykz({
					"bkzcode": this.bkzcode, //#考证code
				}).then(res => {
					
					let baseinfo = res.data.base_info
					this.form = {
						...this.form,
						...baseinfo
					}
					console.log('支付考试赋值后：', this.form)
					// 获取当前考证等级
					this.getLevels(baseinfo.bkz_levels)				
					
				})
			},	
					
			// 获取考证等级
			getLevels(levelArray) {
				this.levelRage = []
				for(let i=0; i<levelArray.length; i++) {
					this.levelRage.push(levelArray[i].kzl_levelname)
				}
			},
			
			// 获取鉴定等级字典
			getDictList(code) {
				this.$u.api.querydict({
					"dictcode": code
				}).then(res => {
					// console.log('dict:', res,code)
					let tmpDict = res.data.base_info
					if(String(code) == "0") {	
						this.jdDictCode = tmpDict.find(item => item.dict_name === "鉴定等级").dict_code;
						this.getDictList(this.jdDictCode)
					} else {
						// 具体鉴定项
						this.jdRange = []
						for(let i=0; i<tmpDict.length; i++) {
							this.jdRange.push(tmpDict[i].dict_name)
						}						
					}					
				})
			},
			
			// 门头照上传			
			afterDoorPhotoRead(event) {
				this.doorPhotos = event.file;
			},
			deleteDoorPhoto(index) {
				this.doorPhotos.splice(index, 1);
			},

			// 显示经营类型弹窗
			isShowPicker(value) {
				
				if (value == 0) {
					
					this.NumberValue = value;
					this.mode = "selector";
					this.range = this.levelRage
					this.defaultSelector = [0];
					uni.hideKeyboard();
				} else if (value == 1) {
					this.NumberValue = value;
					this.mode = "selector";
					// this.range = ['初次鉴定', '二次鉴定'];
					this.range = this.jdRange
					this.defaultSelector = [0];
					uni.hideKeyboard();
				} else {
					this.NumberValue = value;
					this.mode = "region"
					uni.hideKeyboard();
					// this.range = [['亚洲', '欧洲'], ['中国', '日本'], ['北京', '上海', '广州']];
					// this.defaultSelector = [0, 0, 0];
				}
				this.show = true
			},

			// 计算企业介绍内字数
			handleInput() {
				// 计算当前字数（考虑中文和符号）
				this.currentCount = this.introduction.length

				// 如果超过最大字数，截取前1000个字符
				if (this.currentCount > this.maxCount) {
					this.introduction = this.introduction.substring(0, this.maxCount)
					this.currentCount = this.maxCount
				}
			},

			// 选择确认
			confirm(e) {				
				if (this.NumberValue == 0) {
					// 报考等级
					this.form.bkzLevels = this.range[e[0]];
					this.chanageLevels()
				} else if (this.NumberValue == 1) {
					this.form.jdclassfiy = this.range[e[0]];
				} else {
					this.form.businessAddress = e.province.label + '-' + e.city.label + '-' + e.area.label;;
				}
			},
			
			// 是否参加培训
			isTraining(params) {
				console.log('istrain：',params)
				if(params.value) {
					// 参加培训㹖true
					// 培训金额
					this.kzlFortrainprice = this.form.selectedfl.kzl_fortrainprice ? this.form.selectedfl.kzl_fortrainprice : 0
					// 总金额
					this.form.orderSum = parseFloat(this.kzlPrice)+parseFloat(this.kzlFortrainprice)
					// 需要支付金额
					this.form.orderPay = parseFloat(this.form.orderSum)-parseFloat(this.form.orderJf)
				} else {
					// 不参加培训false
					// 培训金额
					this.kzlFortrainprice = 0
					// 总金额
					this.form.orderSum = parseFloat(this.kzlPrice)+parseFloat(this.kzlFortrainprice)
					// 需要支付金额
					this.form.orderPay = parseFloat(this.form.orderSum)-parseFloat(this.form.orderJf)
				}
			},
			
			// 报考等级后的显示培训
			chanageLevels() {
				console.log('福利课程-1：',this.form)
				for(let i=0; i<this.form.bkz_levels.length; i++) {
					if(this.form.bkzLevels == this.form.bkz_levels[i].kzl_levelname) {
						// 取得等级中是否培训
						this.form.boxchecked = String(this.form.bkz_levels[i].kzl_fortrain) == "1" ? true : false
						// 取得福利课程与题库
						this.form.selectedfl = {}
						this.form.selectedfl = this.form.bkz_levels[i]
						this.form.selectedflkc = this.form.selectedfl.kcfl.map(item => item.kzl_flkc?.bc_name).filter(Boolean).join('、')
						this.form.selectedfltk = this.form.selectedfl.tkfl.map(item => item.kzl_fltk?.btk_name).filter(Boolean).join('、')
						// 订单金额
						this.kzlPrice = this.form.selectedfl.kzl_price ? this.form.selectedfl.kzl_price : 0
						// 培训金额
						this.kzlFortrainprice = this.form.selectedfl.kzl_fortrainprice ? this.form.selectedfl.kzl_fortrainprice : 0
 						// 总金额
						this.form.orderSum = parseFloat(this.kzlPrice)+parseFloat(this.kzlFortrainprice)
						// 需要支付金额
						this.form.orderPay = parseFloat(this.form.orderSum)-parseFloat(this.form.orderJf)
						console.log('福利课程：',this.form.orderSum)
						
					}
				}
				console.log('所选择：',this.form)
			},

			// 经营类型选择
			confirmBusinessType(e) {
				this.form.businessType = e.value[0].label;
				this.showBusinessTypePicker = false;
			},

			// 地址选择
			confirmAddress(e) {
				const [province, city, district] = e.value;
				this.form.businessAddress = `${province.name}-${city.name}-${district.name}`;
				this.showAddressPicker = false;
			},
			
			// 支付明细单选
			selectPayment(type) {
			  // 单选逻辑
			  if (type === 'wechat') {
			    this.payment.wechat = true
			    this.payment.other = false
					this.form.orderzflx = 'wechar'
			  } else {
			    this.payment.wechat = false
			    this.payment.other = true
					this.form.orderzflx = 'other'
			  }
			},

			// 上一步
			handlePrev() {
				uni.navigateBack();
			},

			// 提交
			handleSubmit() {
				// 判断是否邀请码进来
				// 是否有机构code,报名考证的ywcode= kzbm
				if(!this.form.bkzLevels) {
					uni.showToast({
					  title: '报考等级不能为空',
					  icon: 'fail'
					});
					return
				}
				this.loading = true;
				let getLinkcode = uni.getStorageSync('linkcode');
				let getYwCode = uni.getStorageSync('ywcode');
				// 若两个都为真，则是邀请链接进来
				if(getLinkcode && getYwCode === 'kzbm') {
					// 考证报名
					this.apiCreatekzbm(getLinkcode,getYwCode)
					// 考证订单
					setTimeout(() => {
						this.apiCreatekzorder()
					},1000)					
					this.loading = false;
				} else {
					this.apiCreatekzbm("0","0")
					this.loading = false;
					setTimeout(() => {
						this.apiCreatekzorder()
					},1000)	
				}			

			},
			//从业者从机构的邀请链接进入创建考证报名
			apiCreatekzbm(linkcode,ywcode) {
				this.$u.api.cyzcreatekzbm({
					"usercode":uni.getStorageSync('usercode'), //#用户编号
					"jgkzcode":linkcode,//#机构分享的邀请链接中的机构考证code
					"bkzcode": this.form.bkz_code,//#考证编号
					"kzlcode": this.form.selectedfl.kzl_code,//#报考级别编号
					"ukzjdfl": this.form.jdclassfiy,//#鉴定分类，默认为首次鉴定
					"ukzjointrain": this.form.boxchecked === false ? 0 : 1,//#是否参加培训
					"ukzorderminus":this.form.orderPay,//#订单优惠金额
				}).then (res => {
					console.log('提交支付', res)		
				})
			},
			// 考证订单
			apiCreatekzorder() {
				this.$u.api.createkzorder({
					"bkzcode": this.form.bkz_code,  //#考证code
					"usercode":uni.getStorageSync('usercode'), //#从业用户编号
					"wxopenid": uni.getStorageSync('wxopenid'), ///openid
					// "payprice":this.form.orderPay, //#支付价格
					"payprice":0.01,
					"yhprice": this.form.orderJf,  //#优惠价格,若无，直接传0
					"paytype": 0,  //#支付类型，0微信，1线下
				}).then(res => {
					console.log('订单：',res)
					let baseinfo = res.data.base_info
					this.appid = baseinfo.appId    ////wx的appid
					this.nonceStr= baseinfo.nonceStr  ///阿布字符串
					this.package= baseinfo.package   //固定值 
					this.paySign= baseinfo.paySign   //微信支付商户号
					this.signType= baseinfo.signType   //统一下单号
					this.timeStamp= baseinfo.timeStamp   //时间戳（单位：秒杀）	
					// 调走微信支付
					this.wxplayquestion()		
				})				
			},
			
			
			// 调走微信支付
			wxplayquestion() {
				// 将 uni.requestPayment 包装为 Promise
				new Promise((resolve, reject) => {
						uni.requestPayment({
								provider: 'wxpay',
								timeStamp: this.timeStamp,
								nonceStr: this.nonceStr,
								package: this.package,
								signType: this.signType,
								paySign: this.paySign,
								success: resolve,
								fail: reject
						});
				})
				.then((res) => {
						// 微信支付成功
						setTimeout(() => {
								console.log('pay-success:' + JSON.stringify(res));
								uni.showToast({
										title: '支付成功！',
										icon: 'none'
								});
						}, 2000);
						uni.navigateTo({
							url: '/pages/Practitioner/instiVisitPract/instiVisitFinish'
						})
				})
				.catch((err) => {
						console.log('pay-fail:' + JSON.stringify(err));
				});
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		// padding: 10rpx;
		// background-color: #f5f5f5;
		// min-height: 100vh;

		.required {
			color: #f56c6c;
		}

		/deep/ .u-steps {
			background: #fff;
			padding: 30rpx;
			border-radius: 12rpx;
			margin-bottom: 30rpx;
		}

		.introduction {
			padding: 10px 0rpx;
			background-color: #fff;

			.header {
				margin-bottom: 10rpx;
				display: flex;

				.title {
					// font-size: 36rpx;
					// font-weight: bold;
					color: #333;
				}
			}

			.textarea-container {
				position: relative;

				/deep/ .u-input__textarea {
					padding: 20rpx;
					background-color: #f5f5f5;
					border-radius: 10rpx;
					font-size: 28rpx;
				}

				.word-count {
					position: absolute;
					right: 20rpx;
					bottom: 20rpx;
					font-size: 24rpx;
					color: #999;
					background-color: rgba(245, 245, 245, 0.7);
					padding: 0 10rpx;
					border-radius: 4rpx;
				}
			}
		}


		.form-container {
			background: #fff;
			padding: 20rpx;
			border-radius: 12rpx;

			/deep/ .u-field {
				padding: 10px 0;
			}

			/deep/ .u-form-item__label {
				.required {
					color: #f56c6c;
					margin-right: 4rpx;
				}
			}

			.upload-section {
				margin-bottom: 40rpx;

				.upload-title {
					font-size: 28rpx;
					color: #606266;
					margin-bottom: 16rpx;
					display: block;

				}
			}
			
			// 选择是否参加
			.checkbox-container {
				display: flex;
				justify-content: space-between;
				margin: 20rpx 0;
				line-height: 16px;
			}	
			
			
			.text-container {
				background-color: #e7ebf3;
				border-radius: 12rpx;
				display: flex;
		    flex-direction: column;
				padding: 20rpx;
				font-size: 8px;
				margin-bottom: 10px;
			}

			.button-group {
				// display: flex;
				// justify-content: space-between;
				margin: auto;
				// margin-top: 60rpx;

				// 此样式主要为了适配wx小程序的按钮
				/deep/ .u-size-default {
					width: 350px;
					
				}

				.u-btn {
					flex: 1;
				}
			}
		}
		
		// 支付明细
		.invitation-popup {
		  // height: 70vh;
		  display: flex;
		  flex-direction: column;
			
			.popup-header {
			  padding: 30rpx;
			  text-align: center;
			  border-bottom: 1rpx solid #f5f5f5;
			}
				
			.container {
			  padding: 20rpx;
			  padding-bottom: 120rpx;
			  background-color: #f7f7f7;
			  min-height: 100vh;
			}
			
			.card {
			  background-color: #fff;
			  border-radius: 12rpx;
			  padding: 24rpx;
			  margin-bottom: 20rpx;
			  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			}
			
			.goods-item {
			  display: flex;
			  justify-content: space-between;
			  align-items: center;
			  padding: 20rpx 0;
			  border-bottom: 1rpx solid #f5f5f5;
			  
			  &:last-child {
			    border-bottom: none;
			  }
			}
			
			.goods-info {
			  flex: 1;
			  display: flex;
			  align-items: center;
			  overflow: hidden;
			}
			
			.goods-name {
			  font-size: 28rpx;
			  color: #333;
			  overflow: hidden;
			  text-overflow: ellipsis;
			  white-space: nowrap;
			  max-width: 40%;
			}
			
			.goods-level {
			  font-size: 24rpx;
			  color: #999;
			  margin: 0 10rpx;
			}
			
			.goods-price {
			  font-size: 26rpx;
			  color: #ff4d4f;
			}
			
			.goods-count {
			  font-size: 26rpx;
			  color: #666;
			}
			
			.amount-item {
			  display: flex;
			  justify-content: space-between;
			  margin-bottom: 16rpx;
			  font-size: 26rpx;
			  color: #666;
			}
			
			.total-amount {
			  display: flex;
			  justify-content: flex-end;
			  margin-top: 20rpx;
			  font-size: 28rpx;
			  font-weight: bold;
			  
			  .price {
			    color: #ff4d4f;
			    margin-left: 10rpx;
			  }
			}
			
			.section-title {
			  font-size: 28rpx;
			  font-weight: bold;
			  margin-bottom: 20rpx;
			}
			
			.payment-item {
			  display: flex;
			  align-items: center;
			  padding: 20rpx 0;
			  border-bottom: 1rpx solid #f5f5f5;
			  
			  &:last-child {
			    border-bottom: none;
			  }
			}
			
			.payment-info {
			  display: flex;
			  align-items: center;
			  margin-left: 20rpx;
			  font-size: 26rpx;
			}
			
			.payment-icon {
			  width: 40rpx;
			  height: 40rpx;
			  margin-right: 15rpx;
			}
			
			.upload-area {
			  margin-top: 20rpx;
			  padding-top: 20rpx;
			  border-top: 1rpx dashed #eee;
			}
			
			.upload-btn {
			  display: flex;
			  flex-direction: column;
			  align-items: center;
			  justify-content: center;
			  width: 200rpx;
			  height: 200rpx;
			  background-color: #f7f7f7;
			  border-radius: 8rpx;
			  color: #999;
			  font-size: 24rpx;
			}
			
			.footer {
			  position: fixed;
			  bottom: 0;
			  left: 0;
			  right: 0;
			  padding: 20rpx;
			  background-color: #fff;
			  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
			  
			  /deep/ .u-btn {
			    height: 80rpx;
			    font-size: 30rpx;
			  }
			}	
		}	
	}
</style>